<?php

namespace app\admin\controller;

use app\model\Platform;
use app\model\PlatformScheme;
use think\exception\ValidateException;
use app\model\Files;
use app\model\Users;
use app\model\AdminMenu;
use app\model\UsersRoles;

class SysbaseController extends Base
{
	/*
 	* @Description 图片管理列表
 	*/
	function fileList()
	{
		$limit  = $this->request->post('limit', 20, 'intval');
		$page = $this->request->post('page', 1, 'intval');

		$where = [];

		$field = 'id,filepath,hash,create_time';

		$res = Files::where($where)->field($field)->order('id desc')->paginate(['list_rows' => $limit, 'page' => $page])->toArray();

		$data['data'] = $res;
		return $this->json($data);
	}

	/*
 	* @Description  删除图片
 	*/
	function deleteFile()
	{
		$filepath =  $this->request->post('filepath', '', 'serach_in');
		if (!$filepath) $this->error('请选择图片');

		Files::where('filepath', 'in', $filepath)->delete();

		return $this->json(['msg' => '操作成功']);
	}
	public function sysversion()
	{
		if (config('database.app_name') == config('my.app_v2')) {
			return $this->json(['data' => 'v2']);
		} elseif (config('database.app_name') == config('my.app_v3')) {
			return $this->json(['data' => 'v3']);
		} elseif (config('database.app_name') == config('my.app_v6')) {
			return $this->json(['data' => 'v6']);
		}
	}

	/*
 	* @Description  重置密码
 	*/
	public function resetPwd()
	{
		$password = $this->request->post('password');

		if (empty($password)) $this->error('密码不能为空');

		$data['id'] = $this->userInfo['id'];

		$data["salt"] = substr(md5(uniqid()), 8, 8);

		$data['password'] = pass_hash($password, $data["salt"]);

		$res = Users::update($data);

		return $this->json(['msg' => '操作成功']);
	}


	/*
 	* @Description  清除缓存
 	*/
	public function clearCache()
	{
		$appname = app('http')->getName();
		try {
			deldir(app()->getRootPath() . 'runtime/cache');
		} catch (\Exception $e) {
			abort(config('my.error_log_code'), $e->getMessage());
		}
		return $this->json(['msg' => '操作成功']);
	}

	public function getModules($pid = 0)
	{
		$field = 'id,title,path,status,icon,sort';
		$query = AdminMenu::field($field)->where(['pid' => $pid, 'status' => 1]);

//		$query->where('is_module', 1);

		if (config('database.app_name') == config('my.app_v2')) {
			$query->where('is_v2', 1);
		}

		if (config('database.app_name') == config('my.app_v3')) {
			$query->where('is_v3', 1);
		}
		if (config('database.app_name') == config('my.app_v6')) {
			$query->where('is_v6', 1);
		}

		$menus = $query->order('sort asc')->select()->toArray();
        foreach ($menus as &$val){
            $val['children'] = AdminMenu::field($field)->where(['pid' => $val['id'], 'status' => 1])->order('sort asc')->select()->toArray();
            if($val['children']){
                foreach ($val['children'] as &$v) {
                    $children = AdminMenu::field($field)->where(['pid' => $v['id'], 'status' => 1])->order('sort asc')->select()->toArray();
                    if ($children) {
                        foreach ($children as $k1 => $v1) {
                            $children[$k1]['title'] = $v1['title'] . '' . '(' . $v1['path'] . ')';
                            $children[$k1]['children'] = AdminMenu::field($field)->where(['pid' => $v1['id'], 'status' => 1])->order('sort asc')->select()->toArray();
                        }
                    }
                    $v['children'] = $children;
                }
            }
        }
		return $this->json(['menus' => $menus]);
	}

	public function getRolesMenus()
	{
		$menu = $this->getAdminMenus(0);
		if (!empty($menu)) {
			$order_array = array_column($menu, 'sort');	 //数组排序 根据
			array_multisort($order_array, SORT_ASC, $menu);
		}
		return $this->json(['menus' => $menu]);
	}

    public function getRolesMenusUser()
    {
        $weid = $this->request->param('weid');
        $weid = $weid ? $weid : weid();
        $platFormInfo = Platform::where(['id' => $weid])->find();
        if($platFormInfo['scheme_id']){
            $platFormSchemeInfo = PlatformScheme::where(['id'=>$platFormInfo['scheme_id']])->find();
            $menu = $this->getAdminMenusUser(0, $platFormSchemeInfo['access']);
            if (!empty($menu)) {
                $order_array = array_column($menu, 'sort');	 //数组排序 根据
                array_multisort($order_array, SORT_ASC, $menu);
            }
            return $this->json(['menus' => $menu]);
        }else{
            $menu = $this->getAdminMenus(0);
            if (!empty($menu)) {
                $order_array = array_column($menu, 'sort');	 //数组排序 根据
                array_multisort($order_array, SORT_ASC, $menu);
            }
            return $this->json(['menus' => $menu]);
        }
    }

    public function getRolesMenusDivide()
    {
        $menu = $this->getAdminMenusDivide(0);
        if (!empty($menu)) {
            $order_array = array_column($menu, 'sort');	 //数组排序 根据
            array_multisort($order_array, SORT_ASC, $menu);
        }
        return $this->json(['menus' => $menu]);
    }



	//权限系统获取菜单
	private function getAdminMenus($pid)
	{
		$field = 'id,pid,title,path,status,icon,sort,is_show';
		$rolesInfo = UsersRoles::getinfo($this->userInfo);

		$query = AdminMenu::field($field)->where(['pid' => $pid, 'status' => 1]);
		if ($rolesInfo['is_allrole'] != 1 && $rolesInfo['pid'] != 0) {
			$query->where('path', 'in', $rolesInfo['access']);
		}

		if (!empty($this->sid)) {
			$query->where('is_store', 1);
		} elseif (!empty($this->cashregister)) {
			$query->where('is_cashregister', 1);
		} elseif (!empty($this->ocid)) {
			$query->where('is_city', 1);
		} elseif (!empty($this->tzid)) {
			$query->where('is_tuanzhang', 1);
		} elseif ($this->console == 1) {
			$query->where('is_console', 1);
		} else {
			$query->where(function ($q) {
				$q->where('is_admin', 1)->whereOr('is_store', 1)->whereOr('is_cashregister', 1)->whereOr('is_city', 1)->whereOr('is_tuanzhang', 1);
			});
		}

		if (config('database.app_name') == config('my.app_v2')) {
			$query->where('is_v2', 1);
		}

		if (config('database.app_name') == config('my.app_v3')) {
			$query->where('is_v3', 1);
		}
		if (config('database.app_name') == config('my.app_v6')) {
			$query->where('is_v6', 1);
		}

		$list = $query->order('sort asc')->select()->toArray();
//        echo $query->getLastSql();

		if ($list) {
			foreach ($list as $key => $val) {
				$menus[$key]['id'] = $val['id'];
				$menus[$key]['pid'] = $val['pid'];
				$menus[$key]['sort'] = $val['sort'];
				$menus[$key]['access'] = $val['path'];
				$menus[$key]['is_show'] = $val['is_show'];
                $menus[$key]['name'] = $val['title'];
				$menus[$key]['title'] = $val['title'] . '' . '(' . $val['path'] . ')';

				$sublist = AdminMenu::field($field)
					->where(['pid' => $val['id'], 'status' => 1])
					->order('sort asc')
					->select()
					->toArray();
				if ($sublist) {
					$menus[$key]['children'] = $this->getAdminMenus($val['id']);
				}
			}
			if (is_array($menus)) {
				$menus = array_values($menus);
			}
			return $menus;
		}
	}

    private function getAdminMenusUser($pid, $access='')
    {
        $field = 'id,pid,title,path,status,icon,sort,is_show';
        $rolesInfo = UsersRoles::getinfo($this->userInfo);
        $query = AdminMenu::field($field)->where(['pid' => $pid, 'status' => 1]);
        if ($rolesInfo['is_allrole'] != 1 && $rolesInfo['pid'] != 0) {
            $query->where('path', 'in', $rolesInfo['access']);
        }

        if(!empty($access)){
            $query->where('id', 'in', $access);
        }

        if (!empty($this->sid)) {
            $query->where('is_store', 1);
        } elseif (!empty($this->cashregister)) {
            $query->where('is_cashregister', 1);
        } elseif (!empty($this->ocid)) {
            $query->where('is_city', 1);
        } elseif (!empty($this->tzid)) {
            $query->where('is_tuanzhang', 1);
        } elseif ($this->console == 1) {
            $query->where('is_console', 1);
        } else {
            $query->where(function ($q) {
                $q->where('is_admin', 1)->whereOr('is_store', 1)->whereOr('is_cashregister', 1)->whereOr('is_city', 1)->whereOr('is_tuanzhang', 1);
            });
        }

        if (config('database.app_name') == config('my.app_v2')) {
            $query->where('is_v2', 1);
        }

        if (config('database.app_name') == config('my.app_v3')) {
            $query->where('is_v3', 1);
        }
        if (config('database.app_name') == config('my.app_v6')) {
            $query->where('is_v6', 1);
        }

        $list = $query->order('sort asc')->select()->toArray();
//        echo $query->getLastSql();

        if ($list) {
            foreach ($list as $key => $val) {
                $menus[$key]['id'] = $val['id'];
                $menus[$key]['pid'] = $val['pid'];
                $menus[$key]['sort'] = $val['sort'];
                $menus[$key]['access'] = $val['path'];
                $menus[$key]['is_show'] = $val['is_show'];
                $menus[$key]['name'] = $val['title'];
                $menus[$key]['title'] = $val['title'] . '' . '(' . $val['path'] . ')';

                $sublist = AdminMenu::field($field)
                    ->where(['pid' => $val['id'], 'status' => 1])
                    ->order('sort asc')
                    ->select()
                    ->toArray();
                if ($sublist) {
                    $menus[$key]['children'] = $this->getAdminMenusUser($val['id'], $access );
                }
            }
            if (is_array($menus)) {
                $menus = array_values($menus);
            }
            return $menus;
        }
    }

    private function getAdminMenusDivide($pid = 0)
    {
        $field = 'id,pid,title,path,status,icon,sort,is_show';
//        $rolesInfo = UsersRoles::getinfo($this->userInfo);
        $map = [
            ['status', '=', 1],
            ['pid', '=', $pid],
            ['is_v3', '=', 1],
        ];

        $where = [
            'is_admin' =>  1,
            'is_store' => 1,
            'is_cashregister' => 1,
            'is_city' => 1,
            'is_tuanzhang' => 1,
        ];
        $list = AdminMenu::field($field)->where($map)->where(function($query) use ($where){$query->whereOr($where);})->order('sort asc')->select()->toArray();
        if ($list) {
            foreach ($list as $key => $val) {
                $menus[$key]['id'] = $val['id'];
                $menus[$key]['pid'] = $val['pid'];
                $menus[$key]['icon'] = $val['icon'];
                $menus[$key]['sort'] = $val['sort'];
                $menus[$key]['access'] = $val['path'];
                $menus[$key]['is_show'] = $val['is_show'];
                $menus[$key]['title'] = $val['title'];
                $menus[$key]['name'] = $val['title'] . '' . '(' . $val['path'] . ')';

                $sublist = AdminMenu::field($field)->where(['pid' => $val['id'], 'status' => 1])->order('sort asc')->select()->toArray();

                if ($sublist) {
                    foreach ($sublist as $k => $v){
                        $sublist[$k]['title'] = $v['title'] . '' . '(' . $v['path'] . ')';
                        $children = AdminMenu::field($field)->where(['pid' => $v['id'], 'status' => 1])->order('sort asc')->select()->toArray();
                        if ($children) {
                            foreach ($children as $k1 => $v1) {
                                $children[$k1]['title'] = $v1['title'] . '' . '(' . $v1['path'] . ')';
                                $children[$k1]['children'] = AdminMenu::field($field)->where(['pid' => $v1['id'], 'status' => 1])->order('sort asc')->select()->toArray();
                            }
                        }
                        $sublist[$k]['children'] = $children;

                    }
                    $menus[$key]['children'] = $sublist;
                }
            }
            if (is_array($menus)) {
                $menus = array_values($menus);
            }
            return $menus;
        }
    }

    public function get_menu_detail()
    {
        if(request()->isPost()){
            $id = input('id');
            $data = AdminMenu::where(['id'=>$id])->find();
            $data['pid_title'] = AdminMenu::where(['id'=>$data['pid']])->value('title');
            return $this->json(['menus' => $data]);
        }
    }

    public function get_menu_update()
    {
        if(request()->isPost()){
            $data = input('post.');
            $state = AdminMenu::where(['id'=>$data['id']])->update([
                'title' => $data['title'],
                'pid' => $data['pid']
            ]);
            if($state){
                return $this->json(['code'=>2000,'msg'=>'修改成功']);
            }else{
                return $this->json(['code'=>2001, 'msg'=>'修改失败']);
            }
        }
    }
}
